package com.wlyuan.open.scanner.application.handler.table;

import com.alibaba.fastjson.JSON;
import com.wlyuan.open.scanner.application.annotation.TableScannerName;
import com.wlyuan.open.scanner.constant.ScannerCodeEnum;
import com.wlyuan.open.scanner.constant.TableEnum;
import com.wlyuan.open.scanner.repository.FinanceBillRepository;
import com.wlyuan.open.scanner.utils.enums.bill.BillStatusEnum;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author lijing
 * @description
 */
@Slf4j
@Service
@RequiredArgsConstructor
@TableScannerName(isDefault = false, tableName = TableEnum.BILL)
public class BillTableToIncrHandler extends BaseTableToIncrHandler {
    private final FinanceBillRepository financeBillRepository;
    private static final String INDEX_STATUS = "Index_Status";
    private static final String INDEX_ID = "Index_ID";
    private static final String BILL_TYPE = "Index_BillType";
    private static final String INDEX_CREATE_COMPANY_ID = "Index_OwnerCompanyID";
    private static final String INDEX_SRC_ID = "Index_SrcID";

    @Override
    public List<String> handler(String tableName, String data, String beforeData) {
        var businessParams = params(data);
        if (StringUtils.isBlank(businessParams)) {
            return Collections.emptyList();
        }
        return Arrays.asList(ScannerCodeEnum.BILL.getName());
    }

    private String params(String data) {
        var map = JSON.parseObject(data, Map.class);
        var status = String.valueOf(map.get(INDEX_STATUS));
        //只同步已对账和已结算的对账单
        if (!BillStatusEnum.isAlready(Integer.valueOf(status))) {
            logger.error("对账单状态不是草稿或审核中或已结帐或者已对账：{}", status);
            return "";
        }

        saveUpAndDown(map);
        return status;
    }

    private void saveUpAndDown(Map<String, Object> map) {
        financeBillRepository.save(Long.valueOf(String.valueOf(map.get(INDEX_ID))),
                Integer.valueOf(String.valueOf(map.get(BILL_TYPE))),
                Long.valueOf(String.valueOf(map.get(INDEX_CREATE_COMPANY_ID))),
                Objects.isNull(map.get(INDEX_SRC_ID)) ? null : Long.valueOf(String.valueOf(map.get(INDEX_SRC_ID)))
        );
    }
}
